#include "debug_log.h"

static FILE* log_file = NULL;

/**
 * @brief Internal logging control function.
 *
 * Handles the actual formatting and output of log messages.
 *
 * @param tag Log level tag (e.g., "INFO", "ERROR", "DEBUG").
 * @param suppress Logging control:
 *                 - 0: Do not print.
 *                 - 1: Print normally.
 *                 - 2: Print with timestamp.
 * @param format Format string (printf-style).
 * @param args Variable argument list.
 */
static void log_control(const char* tag, int suppress, const char* format, va_list args) {
    if (log_file == NULL) {
        log_file = stdout;
    }

    if (suppress == 0) {
        return;
    }

    // Print timestamp if suppress == 2
    if (suppress == 2) {
        time_t now = time(NULL);
        struct tm* tm_info = localtime(&now);
        char time_str[20];
        strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", tm_info);
        fprintf(log_file, "[%s] ", time_str);
    }

    fprintf(log_file, "[%s] ", tag);
    vfprintf(log_file, format, args);
    fprintf(log_file, "\n");

    // Flush buffer if not stdout/stderr
    if (log_file != stdout && log_file != stderr) {
        fflush(log_file);
    }
}

void log_info(int suppress, const char* format, ...) {
    va_list args;
    va_start(args, format);
    log_control("INFO", suppress, format, args);
    va_end(args);
}

void log_error(int suppress, const char* format, ...) {
    va_list args;
    va_start(args, format);
    log_control("ERROR", suppress, format, args);
    va_end(args);
}

void log_debug(int suppress, const char* format, ...) {
    va_list args;
    va_start(args, format);
    log_control("DEBUG", suppress, format, args);
    va_end(args);
}